package com.dou.you.che.web.controller.login;

import com.google.code.kaptcha.Constants;
import com.dou.you.che.comm.annotation.SysLogI;
import com.dou.you.che.comm.utils.response.RspData;
import com.dou.you.che.web.comm.utils.shiro.ShiroUtils;
import com.dou.you.che.web.controller.base.BaseAct;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * 登陆
 * @Author 黄国刚【1058118328@qq.com】
 */
@Controller
public class LoginAct extends BaseAct {

    /**
     * 登录
     */
    @SysLogI("登录")
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public RspData login(String username, String password, String captcha) throws IOException {
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if (null == kaptcha) {
            return RspData.error("验证码已失效");
        }
        if (!captcha.equalsIgnoreCase(kaptcha)) {
            return RspData.error("验证码不正确");
        }

        try {
            Subject subject = ShiroUtils.getSubject();
            //sha256加密
            password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return RspData.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return RspData.error(e.getMessage());
        } catch (LockedAccountException e) {
            return RspData.error(e.getMessage());
        } catch (AuthenticationException e) {
            return RspData.error("账户验证失败");
        }

        return RspData.ok();
    }

    /**
     * 退出
     */
    @SysLogI("退出")
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }
}
